package com.sdry.service.impl.jyy;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.*;
import com.sdry.model.lz.LzQueryCriteria;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.lz.WarehouseRegion;
import com.sdry.model.tdd.emailRecord.EmailRecord;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.jyy.UpService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.utils.DateUtil;
import com.sdry.mapper.barCodeOperation.BarCodeOperationMapper;
import com.sdry.mapper.jyy.ReceiveDetailMapper;
import com.sdry.mapper.jyy.ReceiveMapper;
import com.sdry.mapper.jyy.UpMapper;
import com.sdry.mapper.lz.MaterielMapper;
import com.sdry.mapper.tdd.emailRecord.EmailRecordMapper;
/**
 *
 *@ClassName: UpService
 *@Description: 入库记录
 *@Author jyy
 *@Date 2019-05-17 17:20:06
 *@version 1.0
 *
 *修改人：连雷明
 *修改时间：2019-11-08
 *修改内容：给方法selectByMid2，129行，加参数，仓库ID
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UpServiceImpl implements UpService {
    private final static Logger log = LoggerFactory.getLogger(UpServiceImpl.class);
    private final static int AFFECT_ROW = 0;
    //图片上传路径
    String imgLog = "";
    @Resource
    UpMapper upMapper;
    @Resource
    ReceiveMapper receiveMapper;
    @Resource
    MaterielService materielService;
    @Resource
    ReceiveDetailMapper receiveDetailMapper;
    @Resource
    MaterielMapper materielMapper;
    @Resource
    BarCodeOperationMapper barCodeOperationMapper;
    @Resource
    EmailRecordMapper emailRecordMapper;
    @Resource
    ZcBindAndUnbindService zcBindAndUnbindService;
    /**
     * 根据主键id查询实体
     * @param id 主键id
     * @return 实体
     */
    public Up queryById(Long id) {
        return upMapper.queryById(id);
    }
    /**
     * 条件查询所有
     * @param param 实体条件
     * @return 实体集合
     */
    public List<Up> queryAllByMution(Up param) {
        return upMapper.queryAllByMution(param);
    }
    /**
     * 条件分页查询
     * @param param 实体条件
     * @return 实体集合
     */
    public List<Up> findPageByMution(Up param) {
        return upMapper.findPageByMution(param);
    }
    /**
     * 条件查询记录数
     * @param param 实体条件
     * @return 实体集合
     */
    public Integer selectCountByMution(Up param) {
        return upMapper.selectCountByMution(param);
    }
    /**
     * 插入返回id
     * @param param 实体条件
     * @return 主键id
     */
    public Long insert(Up param) {
        return upMapper.insert(param);
    }
    /**
     * 根据主键更新 返回影响行数
     * @param param 实体条件
     * @return 影响行数
     */
    public Integer update(Up param) {
        return upMapper.update(param);
    }
    /**
     * 根据主键拼接的字符串删除返回影响行数
     * @param ids 主键拼接的字符串
     * @return 影响行数
     */
    public Integer delete(String ids) {
        return upMapper.delete(ids);
    }

    /**
     * 新增物料库存对应关系信息
     */
    @Override
    public Long insertMw(Up up) {
        return upMapper.insertMw(up);
    }
    /**
     * 根据仓库名称查询仓库id
     * @param cqname 仓库名称
     * @return 仓库id
     */
    @Override
    public Long getwidByWname(String cqname) {
        return upMapper.getwidByWname(cqname);
    }
    /**
     * 根据物料id查询库存信息
     * @param mid 料id
     * @return
     */
    @Override
    public ZcInventoryInfoEntity selectByMid(String mid, String batch_num, String warehouse_id) {
        return upMapper.selectByMid(mid, batch_num, warehouse_id);
    }

    /**
     * 根据物料ID，批次，仓库ID，查库存
     * @param mid	物料ID
     * @param batch_num	批次
     * @param warehouseId	仓库ID
     * @return
     *
     * llm 19.11.08 添加参数，warehouseId
     */
    @Override
    public ZcInventoryInfoEntity selectByMid2(String mid, String batch_num, String warehouseId) {
        return upMapper.selectByMid2(mid, batch_num, warehouseId);
    }
    /**
     * 修改库存信息
     * @return
     */
    @Override
    public Long editStock(ZcInventoryInfoEntity zcInventoryInfoEntity) {
        return upMapper.editStock(zcInventoryInfoEntity);
    }
    /**
     * 修改库存信息(计数)
     * @return
     */
    @Override
    public Long editStockOnlyCount(ZcInventoryInfoEntity zcInventoryInfoEntity) {
        return upMapper.editStockOnlyCount(zcInventoryInfoEntity);
    }

    /**
     * 根据产品码和规格型号查询物料
     * @return
     */
    @Override
    public Materiel queryMaterielByRemarkAndSpecification(String remark, String materiel_size, String materiel_properties) {
        return upMapper.queryMaterielByRemarkAndSpecification(remark, materiel_size, materiel_properties);
    }

    /**
     * 根据库区id查找库区名称
     * @param region_id
     * @return
     */
    @Override
    public WarehouseRegion queryRegionNameById(Long region_id) {
        return upMapper.queryRegionNameById(region_id);
    }

    /**
     * 分页查询已收货未入库
     * @param criteria
     */
    @Override
    public List<ReceiveDetailInstock> queryReceiveDetailInstockCriteria(LzQueryCriteria criteria) {
        return upMapper.queryReceiveDetailInstockCriteria(criteria);
    }

    /**
     * 查询已收货未入库的数量
     * @param criteria
     * @return
     */
    @Override
    public int countReceiveDetailInstockCriteria(LzQueryCriteria criteria) {
        return upMapper.countReceiveDetailInstockCriteria(criteria);
    }

    /**
     * 添加库存信息
     * @param zcInventoryInfoEntity
     */
    @Override
    public Long insertStock(ZcInventoryInfoEntity zcInventoryInfoEntity) {
        return upMapper.insertStock(zcInventoryInfoEntity);
    }
    /**
     * 添加库存信息（计数）
     * @param zcInventoryInfoEntity
     */
    @Override
    public Long insertStockOnlyCount(ZcInventoryInfoEntity zcInventoryInfoEntity) {
        return upMapper.insertStockOnlyCount(zcInventoryInfoEntity);
    }

    /**
     * 给不良品绑定条码
     * @param receiveDetail
     */
    @Override
    public void bingdNGCode(ReceiveDetail receiveDetail) {
        upMapper.bingdNGCode(receiveDetail);
    }

    /**
     * 减去已收货未入库数量
     * @param final_value
     */
    @Override
    public void updateReceiveDetailInstockCodeNum(Long id, Long final_value) {
        upMapper.updateReceiveDetailInstockCodeNum(id, final_value);
    }

    /**
     * 根据供应商id查询供应商的邮箱
     * @param customer_id
     * @return
     */
    @Override
    public Customer queryCustomerEmailById(Long customer_id) {
        return upMapper.queryCustomerEmailById(customer_id);
    }

    /**
     * app收货提交
     * @param Details 收货详细
     * @param person 收货人id
     * @param pic_key 图片上传路径
     * @param sure_name 回收容器数量
     * @param warehouse_id
     * @param session
     * @return
     */
    @Override
    public Integer submitReceive(String Details, String person, List<MultipartFile> pic_key,
                                 String sure_name, Long warehouse_id, HttpSession session, String appSubmitStatus) {
        //1、调用文件上传的方法
        imgUpload(session, pic_key);
        //计数循环次数，作用：如果实际收货数量和预计收货数量不相等就不改变收货单状态
        int count = 0;
        //判断收货是否成功的标识
        int successFlag = 0;
        //判断是否修改收货单的数据
        int isUpdate = 0;
        //条码个数
        int codeNums = 0;
        //不质检的自增主键
        Long indentity1 = 0L;
        //质检的自增主键
        Long indentity2 = 0L;
        //拼接条码不重复
        Set<String> set = new HashSet<>();
        String trayStr = "";
        CodeMark codeMark = null;
        Receive receive = null;

        ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = null;
        Gson gson = new Gson();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //接收APP传过来的数据
        List<ReceiveDetail> receiveDetailList = gson.fromJson(Details, new TypeToken<List<ReceiveDetail>>() {}.getType());

        log.info("APP收货提交时传递的参数：Details的条数=" + receiveDetailList.size() + ",提交人的id=" + person +
                ",容器回收的数量=" + sure_name + ",仓库id=" + warehouse_id);
        if(receiveDetailList.size() > AFFECT_ROW){
            //判断条码是否存在
            for (ReceiveDetail receiveDetail : receiveDetailList) {
                for (CodeMark codeMark1 : receiveDetail.getReceiveCode()) {
                    String code = receiveMapper.queryCodeMarkExist(codeMark1.getCode());
                    if(code != null) {
                        successFlag = 0;
                        return successFlag;
                    }
                }
            }

            //遍历收货单详细
            for (ReceiveDetail receiveDetail : receiveDetailList) {
                //app提交的总数
                int beforeValue = 0;
                //质检时多次质检查到的每次的个数
                int singleMaterielCount = 0;
                //拼接的条码字符串
                String addStr = "";
                //收货提交时的条码总数
                for (CodeMark codeMark1 : receiveDetail.getReceiveCode()) {
                    beforeValue += codeMark1.getNum();
                }
                //beforeValue = receiveDetail.getCodeNum();
                //根据收货单详细id查询收货单
                ReceiveDetail receiveDetail1 = receiveDetailMapper.queryReceiveDetailById(receiveDetail.getId());
                if (receiveDetail1 != null) {
                	//app实际收到的总个数
                    receiveDetail.setCodeNum(beforeValue + receiveDetail1.getCodeNum());
                    
                    if (receiveDetail.getCodeNum() == receiveDetail.getTotalNum()) {
                    	count ++;
                    }
                }
                
                //8、根据app提交数量修改收货详细表
                Integer affect3 = receiveDetailMapper.update(receiveDetail);
                if (affect3 == AFFECT_ROW) {
                    //TODO 修改收货详细表数据失败
                    successFlag = -5;
                    return successFlag;
                }

                //根据物料id查询物料
                Materiel materiel = materielService.queryMaterielById(receiveDetail.getMid());
                //根据收货单号查询收货单
                String receiveNumber = receiveDetail.getReceiveNumber();
                receive = new Receive();
                receive.setReceiveNumber(receiveNumber);
                List<Receive> receiveList = receiveMapper.queryAllByMution(receive);

                //如果不质检或者是发货退的
                if (materiel.getIs_check() == 1 || "1".equals(receiveList.get(0).getType())) {
                    //receiveDetail.setCodeNum(receiveDetail.getCodeNum());
                    receiveDetail.setCodeNum(beforeValue + receiveDetail1.getCodeNum());
                    receiveDetail.setRemark(receiveDetail.getId() + "");
                    receiveDetail.setStatus(1);
                    receiveDetail.setCheck_date(sdf.format(new Date()));
                    //lz新增warehouse_id
                    receiveDetail.setWarehouse_id(warehouse_id);
                    //根据物料批次和物料id查询质检实体是否存在
                    List<ReceiveDetailQuality> receiveDetailQualityList = receiveDetailMapper.
                            queryReceiveDetailQualityByPiciAndMid(receiveDetail.getMid() + "", receiveDetail.getPici());
                    //存在
                    if (receiveDetailQualityList.size() > AFFECT_ROW) {
                        indentity1 = receiveDetailMapper.updateReceiveDetailQualityById(receiveDetailQualityList.get(0).getId() + "", beforeValue + receiveDetail1.getCodeNum() + "");
                        indentity1 = receiveDetailQualityList.get(0).getId();
                    } else {
                        //5、给质检表新增数据
                        indentity1 = receiveDetailMapper.addReceiveDetailQuality1(receiveDetail);
                    }
                    if (indentity1 == AFFECT_ROW) {
                        //TODO 质检表新增数据失败
                        successFlag = -1;
                        return successFlag;
                    }
                } else {
                    //如果质检
                    //receiveDetail.setCodeNum(receiveDetail.getCodeNum());
                    receiveDetail.setCodeNum(beforeValue);
                    receiveDetail.setRemark(receiveDetail.getId() + "");
                    receiveDetail.setStatus(0);
                    receiveDetail.setCheck_date(sdf.format(new Date()));
                    //lz新增warehouse_id
                    receiveDetail.setWarehouse_id(warehouse_id);
                    //根据物料批次和物料id查询质检实体是否存在
                    List<ReceiveDetailQuality> receiveDetailQualityList = receiveDetailMapper.
                            queryReceiveDetailQualityByPiciAndMid(receiveDetail.getMid() + "", receiveDetail.getPici());
                    //存在
                    if (receiveDetailQualityList.size() > AFFECT_ROW) {
                        indentity2 = receiveDetailMapper.updateReceiveDetailQualityById(receiveDetailQualityList.get(0).getId() + "", beforeValue + receiveDetail1.getCodeNum() + "");
                        indentity2 = receiveDetailQualityList.get(0).getId();
                    } else {
                        //5、给质检表新增数据
                        indentity2 = receiveDetailMapper.addReceiveDetailQuality(receiveDetail);
                    }
                    if (indentity2 == AFFECT_ROW) {
                        //TODO 质检表新增数据失败
                        successFlag = -1;
                        return successFlag;
                    }
                }

                //遍历收货单详细里的条码集合
                for (CodeMark codeMark1 : receiveDetail.getReceiveCode()) {
                    singleMaterielCount += codeMark1.getNum();
                    //单个条码个数
                    //codeNums += codeMark1.getNum();
                    //addStr += codeMark1.getCode() + ",";
                    set.add(codeMark1.getCode() + ",");
                    //如果供应商没有码
                    if (receiveList.get(0).getBarcode() == 1) {
                        ReceiveMark receiveMark = new ReceiveMark();
                        receiveMark.setCode(codeMark1.getCode());
                        receiveMark.setNum(codeMark1.getNum());
                        receiveMark.setReceive_detail_id(receiveDetail.getId());
                        receiveMark.setSAP_QAD(receiveDetail.getMateriel_num());
                        receiveMark.setWarehouse_id(warehouse_id);
                        //新增供应商条码之前先判断该条码是否存在
                        ReceiveMark existReceiveMark = receiveDetailMapper.queryReceiveMarkByCode(codeMark1.getCode());
                        if (existReceiveMark != null) {
                            //TODO 条码已存在
                            successFlag = 0;
                            return successFlag;
                        } else {
                            //不存在该条码
                            Long affectReceiveMark = receiveDetailMapper.addReceiveMark(receiveMark);
                            if (affectReceiveMark == AFFECT_ROW) {
                                //TODO ReceiveMark表新增数据失败
                                successFlag = -2;
                                return successFlag;
                            }
                        }
                    }

                    //根据收货提交的详细里的条码查询CodeMark中是否存在该条码
                    String code = receiveMapper.queryCodeMarkExist(codeMark1.getCode());
                    //如果不存在
                    if(code == null) {
                        //如果不质检或者是发货退的
                        if (materiel.getIs_check() == 1 || "1".equals(receiveList.get(0).getType())) {
                            codeMark = new CodeMark();
                            //质检表id不是收货详细表id
                            codeMark.setReceive_detail_id(indentity1);
                            codeMark.setCode(codeMark1.getCode());
                            codeMark.setNum(codeMark1.getNum());
                            codeMark.setIs_ng(codeMark1.getIs_ng());
                            //6、给CodeMark绑定条码
                            Long affectCodeMark = receiveDetailMapper.addCodeMark(codeMark);
                            if (affectCodeMark == AFFECT_ROW) {
                                //TODO CodeMark表新增数据失败
                                successFlag = -3;
                                return successFlag;
                            }
                            BarCodeOperation bar = new BarCodeOperation();
                            bar.setBarCode(codeMark1.getCode());
                            bar.setCodeNum(codeMark1.getNum());
                            bar.setBatch(receiveDetail.getPici());
                            bar.setOperator(Long.parseLong(person));
                            bar.setOperatingTime(sdf.format(new Date()));
                            bar.setMaterielId(receiveDetail.getMid());
                            bar.setType("质检");
                            bar.setResult("成功");
                            //lz新增warehouse_id
                            bar.setWarehouse_id(warehouse_id);
                            //7、给历史记录表插入数据
                            barCodeOperationMapper.insert(bar);
                        } else {
                            codeMark = new CodeMark();
                            codeMark.setReceive_detail_id(indentity2);
                            codeMark.setCode(codeMark1.getCode());
                            codeMark.setNum(codeMark1.getNum());
                            codeMark.setIs_ng(codeMark1.getIs_ng());
                            //6、给CodeMark绑定条码
                            Long affectCodeMark = receiveDetailMapper.addCodeMark(codeMark);
                            if (affectCodeMark == AFFECT_ROW) {
                                //TODO CodeMark表新增数据失败
                                successFlag = -3;
                                return successFlag;
                            }
                        }
                        //最内层的循环结束
                    } else {
                        //TODO 条码已存在
                        successFlag = 0;
                        return successFlag;
                    }
                }

                //获取收货单里的每个条码包含的数量
                //int numbers = receiveDetail.getCodeNum();
                //先根据物料id和批次查询条码库存是否存在
                ZcInventoryInfoEntity zcInventoryInfoEntity = upMapper.selectByMid(receiveDetail.getMid() + "",
                        receiveDetail.getPici(), warehouse_id + "");
                //如果存在
                if (zcInventoryInfoEntity != null) {
                    //根据物料id和批次查询的库存数量
                    int mNum = zcInventoryInfoEntity.getmNum();
                    //总数量(个数)
                    zcInventoryInfoEntity.setmNum(singleMaterielCount + mNum);
                    //3、修改库存
                    Long affact1 = upMapper.editStock(zcInventoryInfoEntity);
                    if (affact1 == AFFECT_ROW) {
                        //TODO 修改库存表数据失败
                        successFlag = -4;
                        return successFlag;
                    }
                    //4、将邮件推送信息存入数据库
                    insertEmailInfo(warehouse_id, materiel, zcInventoryInfoEntity);
                } else {
                    //如果不存在
                    ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
                    zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
                    zcInventoryInfoEntity1.setmNum(singleMaterielCount);
                    zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
                    zcInventoryInfoEntity1.setEnterPerson(Long.parseLong(person));
                    zcInventoryInfoEntity1.setWarehouse_id(warehouse_id);
                    //3、新增库存
                    Long affect2 = upMapper.insertStock(zcInventoryInfoEntity1);
                    if (affect2 == AFFECT_ROW) {
                        //TODO 修改库存表数据失败
                        successFlag = -4;
                        return successFlag;
                    }
                    //4、将邮件推送信息存入数据库
                    insertEmailInfo(warehouse_id, materiel, zcInventoryInfoEntity1);
                }

                /********上架(如果ReceiveCode有值则就可以绑定条码)********/
                if (receiveDetail.getReceiveCode().size() > AFFECT_ROW) {
                    //上架到待检区
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                    zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
                    //托盘条码
                    zcMaterielAndTrayEntity.setTray_code(System.currentTimeMillis() + "");
                    for (String str: set) {
                        addStr += str;
                    }
                    //上架的条码
                    zcMaterielAndTrayEntity.setMateriel_code(addStr);
                    //绑定人
                    zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
                    //绑定日期
                    zcMaterielAndTrayEntity.setBinding_date(sdf1.format(new Date()));
                    //物料id
                    zcMaterielAndTrayEntity.setMid(receiveDetail.getMid());
                    //物料批次
                    zcMaterielAndTrayEntity.setmBatch(receiveDetail.getPici());
                    //条码数(非总数)
                    zcMaterielAndTrayEntity.setmNum(beforeValue);
                    Integer affect4 = receiveMapper.insertInspectionArea(zcMaterielAndTrayEntity);
                    if (affect4 == AFFECT_ROW) {
                        //TODO 新增收货上架数据失败
                        successFlag = -6;
                        return successFlag;
                    }
                    //清空set集合
                    set.clear();
                    trayStr += zcMaterielAndTrayEntity.getTray_code() + ",";
                }
                //判断是否修改收货单的数据
                isUpdate = 1;
            }
        } else {
            //接收参数为空
            //TODO 条码已存在
            successFlag = 0;
            return successFlag;
        }
        //先查询托盘库位表是否存在待检区
        ZcTrayAndLocationEntity trayAndLocation = receiveMapper.queryExistDJ(warehouse_id);
        ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
        //新增之前先判断是否存在，如果不存在就添加
        if(trayAndLocation == null) {
            //托盘码
            zcTrayAndLocationEntity.setTray_code(trayStr);
            //上架到待检区
            zcTrayAndLocationEntity.setLocation_code("DJ");
            //上架人
            zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
            //上架日期
            zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
            //仓库id
            zcTrayAndLocationEntity.setWarehouse_id(warehouse_id);
            //库位托盘表新增信息
            Integer affect5 = receiveMapper.insertTrayLocation(zcTrayAndLocationEntity);
            if (affect5 == AFFECT_ROW) {
                //TODO 新增库位托盘表数据失败
                successFlag = -7;
                return successFlag;
            }
        } else {
            //存在就修改
            //托盘码
            zcTrayAndLocationEntity.setTray_code(trayAndLocation.getTray_code() + trayStr);
            //上架人
            zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
            //上架日期
            zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
            //仓库id
            zcTrayAndLocationEntity.setWarehouse_id(warehouse_id);
            //库位托盘表修改
            Integer affect6 = receiveMapper.updateTrayLocation(zcTrayAndLocationEntity);
            if (affect6 == AFFECT_ROW) {
                //TODO 修改库位托盘表数据失败
                successFlag = -7;
                return successFlag;
            }
        }
        
        //9、如果每条记录都匹配，则修改状态
        if (count == receiveDetailList.size()) {
            receive = new Receive();
            receive.setReceiveNumber(receiveDetailList.get(0).getReceiveNumber());
            //收获状态
            receive.setState(1);
            //收货日期
            receive.setReceiveDate(DateUtil.dateFormat3());
            //收货人
            receive.setReceiveName(person);
            //回收容器数量
            receive.setSureName(sure_name);
            //上传图片路径
            receive.setImgLog(imgLog);
            //lz添加warehouse_id
            receive.setWarehouse_id(warehouse_id);
            //10、更改收货单状态为已收货
            if (isUpdate > AFFECT_ROW) {
                //receiveMapper.update(receive);
                receiveMapper.updateReceive(receive);
                //根据收货单号查询收货单
                List<Receive> receiveList = receiveMapper.queryReceiveByReceiveNumber(receiveDetailList.get(0).getReceiveNumber());
                if (receiveList.size() > AFFECT_ROW) {
                	//有单据合并的
                	if (receiveList.get(0).getMerge_flag() != null) {
                		//修改合并的其它收货单状态
                		receiveMapper.updateReceiveByMergeFlag(receiveList.get(0).getMerge_flag());
                	}
                }
                //收货完成修改标识的值
                successFlag = 1;
            }
        } else {
            receive = new Receive();
            receive.setReceiveNumber(receiveDetailList.get(0).getReceiveNumber());
            //收获状态
            receive.setState(0);
            //收货日期
            receive.setReceiveDate(DateUtil.dateFormat3());
            //收货人
            receive.setReceiveName(person);
            //回收容器数量
            receive.setSureName(sure_name);
            //上传图片路径
            receive.setImgLog(imgLog);
            //lz添加warehouse_id
            receive.setWarehouse_id(warehouse_id);
            //10、更改收货单状态为已收货
            if (isUpdate > AFFECT_ROW) {
                //receiveMapper.update(receive);
                receiveMapper.updateReceive(receive);
                //收货完成修改标识的值
                successFlag = 1;
            }
        }
        //图片路径置为空
        imgLog = "";
        //如果不是恶意多次提交则写入数据
        if (isUpdate > AFFECT_ROW) {
            for(ReceiveDetail detail : receiveDetailList){
                BarCodeOperation bar = new BarCodeOperation();
                bar.setBatch(detail.getPici());
                bar.setOperator(Long.parseLong(person));
                bar.setOperatingTime(sdf.format(new Date()));
                bar.setMaterielId(detail.getMid());
                bar.setType("收货");
                bar.setWarehouse_id(warehouse_id);
                if(successFlag > AFFECT_ROW){
                    bar.setResult("成功");
                } else {
                    bar.setResult("失败");
                }
                for(CodeMark codeMark2 : detail.getReceiveCode()){
                    bar.setBarCode(codeMark2.getCode());
                    bar.setCodeNum(codeMark2.getNum());
                    //11、给历史记录表插入数据
                    barCodeOperationMapper.insert(bar);
                }
            }
        }
        return successFlag;
    }

    /**
     * 图片上传
     * @param session session
     * @param pic_key 图片上传文件名
     */
    public void imgUpload(HttpSession session, List<MultipartFile> pic_key) {
        if(pic_key.size() > AFFECT_ROW){
            for(MultipartFile f : pic_key){
                if(f != null){
                    // 1.获取原文件名1
                    String oriName = f.getOriginalFilename();
                    // 2.获取原文件图片后缀，以最后的.作为截取(.jpg)1
                    String extName = oriName.substring(oriName.lastIndexOf("."));
                    // 3.生成自定义的新文件名，这里以UUID.jpg|png|xxx作为格式（可选操作，也可以不自定义新文件名）1
                    String uuid = UUID.randomUUID().toString();
                    //组合成新的文件
                    String newName = uuid + extName;
                    // 4.获取要保存的路径文件夹
                    String realPath = session.getServletContext().getRealPath("/images/");
                    // 5.保存
                    String savePath = realPath + "\\" +  newName;
                    imgLog = "/images/" + newName;
                    File desFile = new File(savePath);
                    try {
                        f.transferTo(desFile);
                    } catch (Exception e) {
                        log.info("lz图片上传的方法出现异常");
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 将邮件推送信息存入数据库
     * @param materiel 物料实体
     * @param zcInventoryInfoEntity 库存实体
     */
    public void insertEmailInfo(Long warehouse_id, Materiel materiel, ZcInventoryInfoEntity zcInventoryInfoEntity) {
        //如果库存大于或小于预警值  报警
        String content = "";
        if (materiel != null) {
            String materiel_num = materiel.getMateriel_num();
            //String materiel_name = materiel.getMateriel_name();
            //String people = "";
            if(zcInventoryInfoEntity.getmNum() != null && materiel.getUpper_value() != null) {
                if (zcInventoryInfoEntity.getmNum() >= materiel.getUpper_value()) {
                    content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "大于等于" + materiel.getUpper_value() + "特此报警";
                    //PushExample.testSendPush(content , "库存报警", people, "0");
                } else if (zcInventoryInfoEntity.getmNum() <= materiel.getLower_value()) {
                    content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "低于等于" + materiel.getLower_value() + "特此报警";
                    //PushExample.testSendPush(content , "库存报警", people, "0");
                }

                //根据供应商id查询供应商的邮箱
                Customer customer = upMapper.queryCustomerEmailById(materiel.getCustomer_id());
                if (customer != null && !"".equals(content)) {
                    EmailRecord emailRecord = new EmailRecord();
                    emailRecord.setOperate("入库");
                    emailRecord.setReceivePeopleId(customer.getId());
                    emailRecord.setReceiveDate(DateUtil.dateFormat3());
                    emailRecord.setEmailContent(content);
                    emailRecord.setRemark("0");
                    //lz新增warehouse_id
                    emailRecord.setWarehouse_id(warehouse_id);
                    //4、将邮件推送信息存入数据库
                    emailRecordMapper.insert(emailRecord);
                }
            }
        }
    }

    /**
     * 质检提交
     * @param json 质检实体
     * @param person 质检人
     * @param warehouse_id 仓库id
     */
    @Override
    public Integer updateReceiveDetailQualityAPP(String json, String person, String warehouse_id) {
        int returnStatus = 0;
        String codeStr1 = "";
        String codeStr2 = "";
        ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
        Workload workload;
        //CodeMark codeMark;
        Gson gson = new Gson();
        List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
        //app提交过来的数据不为空
        if (receiveDetailQualityList.size() > AFFECT_ROW) {
            for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
                //根据质检单id查询质检单的状态
                int qualityStatus = receiveDetailMapper.queryReceiveDetailQualityStatusById(receiveDetailQuality.getId());
                if (qualityStatus > AFFECT_ROW) {
                    returnStatus = 0;
                    return returnStatus;
                }
                int singleMaterielCount = 0;
                //质检提交后修改质检表数据
                Long affactRow = receiveDetailMapper.updateReceiveDetailQualityAPP(receiveDetailQuality);
                //如果修改成功则给工作量实体添加数据
                for (int j = 0; j < receiveDetailQuality.getWorkloadList().size(); j++) {
                    workload = new Workload();
                    workload.setReceiveDetailQuality_id(receiveDetailQuality.getId());
                    workload.setWorkman(receiveDetailQuality.getWorkloadList().get(j).getWorkman());
                    workload.setGood_num(receiveDetailQuality.getWorkloadList().get(j).getGood_num());
                    workload.setNgood_num(receiveDetailQuality.getWorkloadList().get(j).getNgood_num());
                    //添加每种物料对应的工作量
                    receiveDetailMapper.addWorkload(workload);
                }
                //现在条码
                List<CodeMark> newCodeMarkList = receiveDetailQuality.getReceiveCode();
                //原有条码
                List<CodeMark> oldCodeMarkList = receiveDetailMapper.queryCodeMarkById(receiveDetailQuality.getId() + "");
                //遍历新生成的集合
                List<CodeMark> codeMarkList3 = getDif(newCodeMarkList, oldCodeMarkList);
                //根据质检单id删除CodeMark
                receiveDetailMapper.deleteCodeMarkByQuality(receiveDetailQuality.getId());

                //根据现在的条码去查询物料托盘表，如果查到看状态是否为1，如果没查到就新增到物料托盘表，托盘库位表新增该托盘
                for (CodeMark codeMark : codeMarkList3) {
                    singleMaterielCount = codeMark.getNum();
                    //绑定新条码
                    receiveDetailMapper.addCodeMark(codeMark);
                    /*根据条码查询物料托盘表是否有该条码
                    zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMark.getCode());*/
                    //如果该条码的属性改变
                    if (codeMark.getIs_ng() == 1) {
                        //1、去更新COdeMark表的条码状态
                        receiveDetailMapper.updateCodeMark(codeMark);
                        //根据这个条码去查到这个物料托盘实体
                        zcMaterielAndTrayEntity = receiveDetailMapper.queryMaterielTrayByCode(codeMark.getCode());
                        //2、将这个条码从原来的托盘中去掉,再将处理过后的条码更新到该托盘上
                        String[] queryCode = zcMaterielAndTrayEntity.getMateriel_code().split(",");
                        if (queryCode.length > AFFECT_ROW) {
                            for (String str : queryCode) {
                                //如果匹配
                                if (!str.equals(codeMark.getCode())) {
                                    codeStr1 += str + ",";
                                }
                            }
                        }
                        //物料托盘表中的数量减去不良条码的数量
                        zcMaterielAndTrayEntity.setmNum(zcMaterielAndTrayEntity.getmNum() - codeMark.getNum());
                        zcMaterielAndTrayEntity.setMateriel_code(codeStr1);
                        receiveDetailMapper.updateMaterielTrayById(zcMaterielAndTrayEntity);
                        //3、给这个新托盘生成新的拼接条码
                        codeStr2 += codeMark.getCode() + ",";
                        //4、将新生成的托盘更新到托盘库位表的DJ区域
                    }
                }

                /*****************上架******************/
                //上架到待检区
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
                //托盘条码
                zcMaterielAndTrayEntity.setTray_code(System.currentTimeMillis() + "");
                //上架的条码
                zcMaterielAndTrayEntity.setMateriel_code(codeStr2);
                //绑定人
                zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
                //绑定日期
                zcMaterielAndTrayEntity.setBinding_date(sdf1.format(new Date()));
                //物料id
                zcMaterielAndTrayEntity.setMid(receiveDetailQuality.getMid());
                //物料批次
                zcMaterielAndTrayEntity.setmBatch(receiveDetailQuality.getPici());
                //条码数(非总数)
                zcMaterielAndTrayEntity.setmNum(singleMaterielCount);
                Integer affect4 = receiveMapper.insertInspectionArea(zcMaterielAndTrayEntity);
                /**************************************/
                //先查询待检区的托盘库位表
                ZcTrayAndLocationEntity trayAndLocation = receiveMapper.queryExistDJ(Long.parseLong(warehouse_id));
                ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
                //存在就修改
                //托盘码
                zcTrayAndLocationEntity.setTray_code(trayAndLocation.getTray_code() + zcMaterielAndTrayEntity.getTray_code() + ",");
                //上架人
                zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
                //上架日期
                zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
                //仓库id
                zcTrayAndLocationEntity.setWarehouse_id(Long.parseLong(warehouse_id));
                //库位托盘表修改
                Integer affect6 = receiveMapper.updateTrayLocation(zcTrayAndLocationEntity);
                returnStatus = 1;
            }
        }
        //----------------------给历史记录表插入数据start-------------------------------------
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(new Date());
        for(ReceiveDetailQuality detail : receiveDetailQualityList){
            BarCodeOperation bar = new BarCodeOperation();
            bar.setBatch(detail.getPici());
            bar.setOperator(Long.parseLong(person));
            bar.setOperatingTime(time);
            bar.setMaterielId(detail.getMid());
            bar.setType("质检");
            //lz新增warehouse_id
            bar.setWarehouse_id(Long.parseLong(warehouse_id));
            if(returnStatus > AFFECT_ROW){
                bar.setResult("成功");
            }else{
                bar.setResult("失败");
            }
            for(CodeMark cm : detail.getReceiveCode()){
                bar.setBarCode(cm.getCode());
                bar.setCodeNum(cm.getNum());
                barCodeOperationMapper.insert(bar);
            }
        }
        //----------------------给历史记录表插入数据end-------------------------------------
        return returnStatus;
    }

    /**
     * 比较集合元素是否相等的工具类
     * @param list1
     * @param list2
     * @return
     */
    private static List<CodeMark> getDif (List<CodeMark> list1, List<CodeMark> list2) {
        List<CodeMark> same = new ArrayList<>();
        List<CodeMark> dif = new ArrayList<>();
        List<CodeMark> now = new ArrayList<>();
        same.addAll(list1);
        //先求出两个list的交集
        same.retainAll(list2);
        dif.addAll(list1);
        dif.addAll(list2);
        //用合集去掉交集，就是不同的元素
        dif.removeAll(same);
        now.addAll(same);
        now.addAll(dif);
        return now;
    }
}
